//
//  HR_AlbumListViewController.m
//  HR_PickKit
//
//  Created by KK on 2017/7/21.
//  Copyright © 2017年 Mac. All rights reserved.
//

#import "HR_AlbumListViewController.h"
#import "HR_AlbumListTableViewCell.h"
#import "HR_Macro.h"
#import "HR_PickViewController.h"
NSString *const cellIdentifier = @"HR_AlbumListTableViewCell";

@interface HR_AlbumListViewController ()<
UITableViewDataSource,
UITableViewDelegate
>

@property (weak, nonatomic) IBOutlet UITableView *albumTableView;

/** title数据源 */
@property (strong, nonatomic) NSMutableArray *albumTitleMarr;
/** 资源结果 */
@property (strong, nonatomic) NSMutableArray *albumFetchResultMarr;

@property (strong, nonatomic) PHFetchOptions *options;
@end

@implementation HR_AlbumListViewController

#pragma mark - ----------   Lifecycle（生命周期） ----------
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getAuthorized];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - ---------- Private Methods（私有方法） ----------

#pragma mark initliaze data(初始化数据)
- (void)configUI{
    [self registerCollcetionViewCell];
}
#pragma mark config control（布局控件）
- (void)registerCollcetionViewCell{
    [self.albumTableView registerNib:[UINib nibWithNibName:@"HR_AlbumListTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellIdentifier];
}
#pragma mark networkRequest (网络请求)

#pragma mark actions （点击事件）

#pragma mark - 处理相册授权
- (void)getAuthorized{
    //判断是否有访问权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusNotDetermined){ //暂没有做出选择
        if (status == PHAuthorizationStatusAuthorized){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self getAllAlbums];
                [self configUI];
            });
        }
        
    } else if (status == PHAuthorizationStatusAuthorized){ //已经授权
        dispatch_async(dispatch_get_main_queue(), ^{
            [self getAllAlbums];
            [self configUI];
        });
    } else if (status == PHAuthorizationStatusRestricted){  //拒绝访问
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    }
}

#pragma mark - 利用photoKit 获取所有的相册（相簿）
- (void)getAllAlbums{
    //获得SmartAlbum相册的集合资源
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHCollection *collection in smartAlbums) {
        if ([collection isKindOfClass:[PHCollection class]]) {
            PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
            PHFetchResult *assetFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:self.options];
            [self.albumTitleMarr addObject:collection.localizedTitle];
            [self.albumFetchResultMarr addObject:assetFetchResult];
            [self.albumTableView reloadData];
        }
    }
    //获得Album相册的集合资源
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    for (PHCollection *collection in userAlbums) {
        if ([collection isKindOfClass:[PHCollection class]]) {
            PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
            PHFetchResult *assetFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:self.options];
            [self.albumTitleMarr addObject:collection.localizedTitle];
            [self.albumFetchResultMarr addObject:assetFetchResult];
            [self.albumTableView reloadData];
        }
    }
}
#pragma mark IBActions （点击事件xib）

#pragma mark - ---------- Public Methods（公有方法） ----------

#pragma mark self declare （本类声明）

#pragma mark override super （重写父类）

#pragma mark setter （重写set方法）

#pragma mark - ---------- Protocol Methods（代理方法） ----------
#pragma mark - UITableViewDelegate && UITableViewDataSource  -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.albumTitleMarr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HR_AlbumListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell updateAlbumImage:self.albumFetchResultMarr[indexPath.row] titleName:self.albumTitleMarr[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HR_PickViewController *pickVC = [[HR_PickViewController alloc]init];
    pickVC.albumTitle = self.albumTitleMarr[indexPath.row];
    pickVC.assetFetchResult = self.albumFetchResultMarr[indexPath.row];
    [self.navigationController pushViewController:pickVC animated:YES];
}
#pragma mark - ---------- Lazy Loading（懒加载） ----------

/** 对使用 PHAsset, PHCollection, PHAssetCollection, 和 PHCollectionLis 的方法时出入的参数,主要对获取到资源做一些配置和排序等,一般为 nil, 默认使用系统的. */
- (PHFetchOptions *)options {
    if (!_options) {
        _options = [[PHFetchOptions alloc] init];
        //通过创建时间加载
        _options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    }
    return _options;
}

- (NSMutableArray *)albumTitleMarr{
    if (!_albumTitleMarr) {
        _albumTitleMarr = [NSMutableArray array];
    }
    return _albumTitleMarr;
}
- (NSMutableArray *)albumFetchResultMarr{
    if (!_albumFetchResultMarr) {
        _albumFetchResultMarr = [NSMutableArray array];
    }
    return _albumFetchResultMarr;
}



@end
